import React, { useContext, useState } from 'react';
import ReactDOM from 'react-dom';
let FormContext = React.createContext()
let ItemContext = React.createContext();
function Form(props) {
  let { initialValues, onFinish, children } = props;
  return <FormContext.Provider value={{ initialValues, onFinish }}>
    <div className="form_box">
      {children}
    </div>
  </FormContext.Provider>
}
function Item(props) {
  let { name, label, children } = props;

  return <ItemContext.Provider value={{ name, label }}>
    <div className="item_box">
      {children}
    </div>
  </ItemContext.Provider>
}
Form.Item = Item
function Input() {
  let Form = useContext(FormContext)
  let Item = useContext(ItemContext)
  let [val, setVal] = useState(Form.initialValues[Item.name])
  return <div>
    <span>{Item.label}</span>
    <input
      type="text"
      value={val}
      onChange={(e) => {
        setVal(e.target.value)
        Form.initialValues[Item.name] = e.target.value
      }}
    />
  </div>
}
function Button(props) {

  let Form = useContext(FormContext)
  return <button onClick={() => {
    Form.onFinish()
  }}>{props.children}</button>
}


class App extends React.Component {
  state = {
    initValue: {
      name: "珠峰",
      age: 12,
      sex: "男"
    }
  }
  onFinish = () => {
    console.log('点击了提交', this.state.initValue)
  }
  render() {
    return <div className=''>
      <Form
        initialValues={this.state.initValue}
        onFinish={this.onFinish}
      >
        <Form.Item
          label="用户名"
          name="name">
          <Input></Input>
        </Form.Item>
        <Form.Item
          label="年龄"
          name="age">
          <Input></Input>
        </Form.Item>
        <Form.Item
          label="性别"
          name="sex">
          <Input></Input>
        </Form.Item>
        <Form.Item>
          <Button>提交</Button>
        </Form.Item>
      </Form>
    </div>;
  }
}

ReactDOM.render(<App />, document.getElementById('root'))